// 时令蔬菜
var __seasonItems = [ 15, 4 ];

$(function() {
	FastClick.attach(document.body);
	window.categories = null;
	load();
}());

function getPrice(price) {
	if(price === '0.0元／500克') {
		return '-';
	}
	return price.replace('元／500克', '');
}

/**
 * 加载菜场下所有蔬菜
 */
function load() {
	gloading.start();
	ghttp.get('/market/' + window.marketId + '/items', null, function(resp) {
		if(!resp.success) {
			gloading.stop();
			return;
		}
		window.categories = resp.result.categories;
		onClickSideTab(0);
		gloading.stop();
	});
}

function appendItem(c) {
	var $content = $('.content');
	var $el = $($('#item-tpl').html());

	var href = '/commodity/' + c.commodityId + '/type/' + c.typeId +
		'?name=' + c.commodity +
		'&price='+getPrice(c.average) +
		'&cid=' + c.commodityId;
	
	$el.attr('data-v', c.commodityId);
	$el.find('a').attr('href', href);
	$el.find('.image').css({ 'background-image': g_image(c.commodity) });
	$el.find('.name').text(c.commodity);
	$content.append($el);
}

/**
 * 渲染日常蔬菜
 */
function renderUsual() {
	var $content = $('.content');
	$content.empty();
	window.categories.forEach(function(item) {
		var commodities = item.commodities;
		commodities.forEach(function(c) {
			var has = false;
			for(var i=0; i<__seasonItems.length;i++) {
				if(c.commodityId == __seasonItems[i]) {
					has = true;
					break;
				}
			}
			if(!has) {
				appendItem(c);
			}
		});
	});
}

/**
 * 渲染时令蔬菜
 */
function renderSeason() {
	var $content = $('.content');
	$content.empty();
	window.categories.forEach(function(item) {
		var commodities = item.commodities;
		commodities.forEach(function(c) {
			for(var i=0; i<__seasonItems.length; i++) {
				if(c.commodityId === __seasonItems[i]) {
					appendItem(c);
					break;
				}
			}
		});
	});
}

/******************************************************************/
function onClickSideTab(index) {
	$('.top-bar-item').removeClass('active');
	$('.top-bar-item-' + index).addClass('active');
	if(index === 0) {
		renderUsual();
	} else {
		renderSeason();
	}
}